<style>
  .cell {
    width: 100px;
    height: 100px;
    background-color: green;
    display: inline-block;
    border: 1px solid white;
    vertical-align: middle;

    line-height: 100px;
    font-size: 50px;
    text-align: center;
  }
</style>

<div id="board"></div>

<script>
  let pattern = [
    [2, 0, 0],
    [0, 1, 0],
    [0, 0, 0]
  ]

  let color = 1

  function show() {
    let board = document.getElementById('board')
    board.innerHTML = ''
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < 3; j++) {
        let cell = document.createElement('div')
        cell.classList.add('cell')
        cell.innerText = pattern[j][i] == 2 ? '×' : pattern[j][i] == 1 ? '○' : ''
        cell.addEventListener('click', () => move(j, i))
        board.appendChild(cell)
      }
      board.appendChild(document.createElement('br'))
    }
  }

  function move(j, i) {
    pattern[j][i] = color
    if (check(pattern, color)) {
      alert(color == 2 ? '× 赢了' : "○ 赢了")
    }
    color = 3 - color
    show()
    if (willWin(pattern, color)) {
      console.log(color === 2 ? '× 要赢了' : "○ 要赢了")
    }
  }
  function check(pattern, color) {
    // 检验行
    for (let i = 0; i < 3; i++) {
      let win = true
      for (let j = 0; j < 3; j++) {
        if (pattern[i][j] !== color) win = false
      }
      if (win) return true
    }
    // 检验列
    for (let i = 0; i < 3; i++) {
      let win = true
      for (let j = 0; j < 3; j++) {
        if (pattern[j][i] !== color) win = false
      }
      if (win) return true
    }
    // 斜线
    {
      let win = true
      for (let j = 0; j < 3; j++) {
        if (pattern[j][2 - j] !== color) win = false
      }
      if (win) return true
    }
    // 反斜线
    {
      let win = true
      for (let j = 0; j < 3; j++) {
        if (pattern[j][j] !== color) win = false
      }
      if (win) return true
    }
    return false
  }

  function clone(pattern) {
    return JSON.parse(JSON.stringify(pattern))
  }

  function willWin(pattern, color) {
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < 3; j++) {
        if (pattern[i][j]) continue
        let tmp = clone(pattern)
        tmp[i][j] = color
        if (check(tmp, color)) {
          return [i, j]
        }
      }
    }
    return null
  }
  function bestChoice(pattern, color) {
    let p;
    if (p = willWin(pattern, color)) {
      return {
        point: p,
        result: 1
      }
    }
    let result = -2
    let point = null
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < 3; j++) {
        if (pattern[i][j]) {
          continue;
        }
        let tmp = clone(pattern)
        tmp[i][j] = color
        let r = bestChoice(tmp, 3 - color).result
        if (-r > result) {
          result = -r
          point = [j, i]
        }
      }
    }
    return {
      point: point,
      result: point ? result : 0
    }
  }
  show(pattern)
</script>
